import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { Component, OnInit, Input, OnDestroy } from '@angular/core';
import { Platform } from '@ionic/angular';
import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';
import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { HttpService } from 'src/app/shared/service/http.service';
@Component({
  selector: 'app-hivideo',
  templateUrl: './hivideo.component.html',
  styleUrls: ['./hivideo.component.scss'],
})
export class HivideoComponent implements OnInit, OnDestroy {

  @Input() videoSrc: any;
  @Input() cssStyle: any;
  @Input() autoPlay: any;
  @Input() autohide = true;
  @Input() index = 0;
  @Input() forVideos = false;
  @Input() playIconCssStyle: any;
  @Input() hivideoidFromVideos: any;
  @Input() videoData: any;
  @Input() link: any; // app-video-image 传来的
  @Input() data: any;
  posterUrl: any;
  hivideoid: any;
  volume = 0;
  videoParent: any;
  video: any;
  videoBar: any;
  videoPlayIcon: any;
  playBtn: any;
  fullBtn: any;
  muteBtn: any;
  seekbar: any;
  curTimeSpan: any;
  totalTimeSpan: any;
  volumebar: any;
  origHeight = 0;
  origWidth = 0;
  options = { autoplay: true, isrotate: true, autoHide: true };
  sourceURL: any;
  userAgent = window.navigator.userAgent.toLowerCase();
  constructor(
    private screenOrientation: ScreenOrientation,
    private appGlobalService: AppGlobalService,
    private pageModalService: PageModalService,
    private platform: Platform,
    public httpService: HttpService,) {

  }
  ngOnInit() {
    // if (this.videoData && this.videoData.autoPlay !== undefined ) {
    //   this.autoPlay = this.videoData.autoPlay === "true";
    // }
    // if (this.videoData && !this.videoData.backNeedPlay) {
    //   setTimeout(() => {
    //     localStorage.setItem('playOn', localStorage.getItem('currentPath'));
    //   }, 200);
    //   if (this.appGlobalService.eventService.eventEmit.listenerCount("playOn") > 0) {
    //     this.appGlobalService.eventService.eventEmit.removeListener("playOn");
    //   }
    //   this.appGlobalService.eventService.eventEmit.on("playOn", (obj) => {
    //     setTimeout(() => {
    //       console.log('playOn !!!!!');
    //       if (obj === localStorage.getItem('currentPath')) {
    //         if (that.video && that.video[that.index]) {
    //           that.video[that.index].play();
    //           that.defSound();
    //         }
    //       }
    //     }, 200);
    //   });
    const that = this;
    if (this.appGlobalService.eventService.eventEmit.listenerCount("stopPlay") > 0) {
      this.appGlobalService.eventService.eventEmit.removeListener("stopPlay");
    }
    this.appGlobalService.eventService.eventEmit.on("stopPlay", (obj) => {
      that.video[this.index].pause();
      if (document.getElementById('toggle-btn-fwvideo' + "-" + that.hivideoid)) {
        document.getElementById('toggle-btn-fwvideo' + "-" + that.hivideoid).style.display = 'block';
      }
      if (that.videoPlayIcon) {
        that.exchangeBtnStatus(that.videoPlayIcon, true);
      }
      if (that.playBtn) {
        that.exchangeBtnStatus(that.playBtn, true);
      }
    });
    // }

    // console.log('初始化视频标签' + this.videoSrc);
    this.hivideoid = "hivideo" + new Date().getTime();
    if (this.hivideoidFromVideos) {
      this.hivideoid = this.hivideoidFromVideos;
    }

    try {
      if (this.videoSrc) {
        this.posterUrl = this.videoSrc;
        // bug-view-6016
        if (this.posterUrl.lastIndexOf('#t=1')) {
          this.posterUrl = this.posterUrl.replace('#t=1', '');
        }
      }
      setTimeout(() => {
        this.videoParent = this.queryById('id-hi-video-wrapper' + this.index);
        const ele = this.querySelectorAll('video[ishivideo="true"]');
        const list: any = [];
        for (let index = 0; index < ele.length; index++) {
          const element = ele[index];
          if (element.id.indexOf(this.hivideoid) > -1) {
            list.push(element);
          }
        }
        this.video = list;
        this.videoBar = this.queryById('id-videoBar' + "-" + this.hivideoid + "-" + this.index);
        this.videoPlayIcon = this.queryById('id-centerPlayIcon' + "-" + this.hivideoid + "-" + this.index);
        this.playBtn = this.queryById('id-playBtn' + "-" + this.hivideoid + "-" + this.index);
        this.fullBtn = this.queryById('id-fullBtn' + "-" + this.hivideoid + "-" + this.index);
        this.muteBtn = this.queryById('id-muteBtn' + "-" + this.hivideoid + "-" + this.index);
        this.seekbar = this.queryById('id-seekbar' + "-" + this.hivideoid + "-" + this.index);
        this.curTimeSpan = this.queryById('id-video-time-current' + "-" + this.hivideoid + "-" + this.index);
        this.totalTimeSpan = this.queryById('id-video-time-total' + "-" + this.hivideoid + "-" + this.index);
        this.volumebar = this.queryById('id-volumebar' + "-" + this.hivideoid + "-" + this.index);
        this.platform.ready().then(() => {
          // 适配安卓手机全屏播放
          // if (this.platform.is('android') && localStorage.getItem('client') !== 'BROWSER') {
          // this.bindFullEventForAndroid();
          // } else {
          this.bindFullEvent();
          // }
          this.bindPlayEvent();
          // this.bindAutoHideControlsEvent(); 工具栏
          this.bindMuteEvent();
          this.bindTimeChangeEvent();
        });
        this.addClass(this.videoBar, "none");
        // todo <!--如果是微信浏览器则显示播放按钮-->
        if (this.userAgent.match(/micromessenger/i) === null) {
          if (this.autoPlay && this.index === 0) {
            if (this.video[this.index].paused) {
              this.playBtn.click();
              this.video[this.index].play(); // 播放视频
            }
            this.exchangeBtnStatus(this.videoPlayIcon, false);
            this.defSound();
          } else {

            this.removeClass(this.videoPlayIcon, "offBtn");
            this.addClass(this.videoPlayIcon, "onBtn");
            this.sourceURL = this.videoSrc + '';
          }
        } else {

          this.removeClass(this.videoPlayIcon, "offBtn");
          this.addClass(this.videoPlayIcon, "onBtn");
          this.sourceURL = this.videoSrc + '';
        }
      }, 200);

    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }

  }

  videoClick(e) {

    if (this.hasClass(this.videoPlayIcon, 'offBtn')) {
      this.video[this.index].pause();
      this.exchangeBtnStatus(this.videoPlayIcon, true);
      if (document.getElementById('toggle-btn-fwvideo' + "-" + this.hivideoid)) {
        document.getElementById('toggle-btn-fwvideo' + "-" + this.hivideoid).style.display = 'block';
      }
    }
    e.stopPropagation();
  }

  bindFullEvent() {
    const self = this;
    ["fullscreenchange", "webkitfullscreenchange", "mozfullscreenchange", "MSFullscreenChange"].forEach((eventType) => {
      const curFullhivideoId = null;
      document.addEventListener(eventType, (event) => {
        if ((curFullhivideoId === document.body.getAttribute("curfullHivideo")) && curFullhivideoId !== self.hivideoid) {
          return;
        }
        const isRotate = self.options.isrotate;
        if (self.isFullScreen()) {
          const cltHeight = isRotate ? window.screen.width : window.screen.height;
          const cltWidth = isRotate ? window.screen.height : window.screen.width;
          if (isRotate && !this.hasClass(self.videoParent, "rotate90")) {
            this.addClass(self.videoParent, "rotate90");
          }
          self.videoParent.style.height = cltHeight + "px";
          self.videoParent.style.width = cltWidth + "px";
        } else {
          if (isRotate) { self.videoParent.className = self.videoParent.className.replace("rotate90", "").trim(); }
          self.videoParent.style.height = this.origHeight + "px";
          self.videoParent.style.width = this.origWidth + "px";
        }
      });
    });

    self.fullBtn.addEventListener("click", () => {
      if (!self.isFullScreen()) {
        document.body.setAttribute("curfullHivideo", self.hivideoid);
        this.origWidth = self.videoParent.offsetWidth;
        this.origHeight = self.videoParent.offsetHeight;
        // go full-screen
        if (self.videoParent.requestFullscreen) {
          self.videoParent.requestFullscreen();
        } else if (self.videoParent.webkitRequestFullscreen) {
          self.videoParent.webkitRequestFullscreen();
        } else if (self.videoParent.mozRequestFullScreen) {
          self.videoParent.mozRequestFullScreen();
        } else if (self.videoParent.msRequestFullscreen) {
          self.videoParent.msRequestFullscreen();
        }
        if (this.platform.is('android') && localStorage.getItem('client') !== 'BROWSER') {
          this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.LANDSCAPE);
        }
        self.exchangeBtnStatus(this.fullBtn, false);
      } else {
        // exit full-screen

        // tslint:disable-next-line:no-string-literal
        if (document['exitFullscreen']) {
          // tslint:disable-next-line:no-string-literal
          document['exitFullscreen']();
          // tslint:disable-next-line:no-string-literal
        } else if (document['webkitExitFullscreen']) {
          // tslint:disable-next-line:no-string-literal
          document['webkitExitFullscreen']();
          // tslint:disable-next-line:no-string-literal
        } else if (document['mozCancelFullScreen']) {
          // tslint:disable-next-line:no-string-literal
          document['mozCancelFullScreen']();
          // tslint:disable-next-line:no-string-literal
        } else if (document['msExitFullscreen']) {
          // tslint:disable-next-line:no-string-literal
          document['msExitFullscreen']();
        }
        if (this.platform.is('android') && localStorage.getItem('client') !== 'BROWSER') {
          this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.PORTRAIT);
        }
        self.exchangeBtnStatus(this.fullBtn, true);
      }
    });
  }
  bindFullEventForAndroid() {
    const self = this;

    self.fullBtn.addEventListener("click", () => {
      const isRotate = self.options.isrotate;
      if (this.fullBtn.className === 'onBtn') {
        document.body.setAttribute("curfullHivideo", self.hivideoid);
        this.origWidth = self.videoParent.offsetWidth;
        this.origHeight = self.videoParent.offsetHeight;
        const cltHeight = isRotate ? window.screen.width : window.screen.height;
        const cltWidth = isRotate ? window.screen.height : window.screen.width;
        if (isRotate && !this.hasClass(self.videoParent, "rotate90")) {
          this.addClass(self.videoParent, "rotate90");
        }
        self.videoParent.style.height = cltHeight + "px";
        self.videoParent.style.width = cltWidth + "px";
        self.exchangeBtnStatus(this.fullBtn, false);
      } else {
        if (isRotate) {
          self.videoParent.className = self.videoParent.className.replace("rotate90", "").trim();
        }
        self.videoParent.style.height = this.origHeight + "px";
        self.videoParent.style.width = this.origWidth + "px";
        self.exchangeBtnStatus(this.fullBtn, true);
      }
    });
  }
  bindPlayEvent() {
    const self = this;
    [self.playBtn, self.videoPlayIcon].forEach((ele) => {
      ele.addEventListener("click", (event) => {
        event = event || window.event;
        if (!self.video[self.index] || (self.link)) { return; }
        if (self.video[self.index].paused) {
          // 微信内置的浏览器还是会报错 故不执行play()
          // if (this.userAgent.match(/micromessenger/i) === null) {
          self.video[self.index].play(); // 报错Uncaught (in promise) DOMException解决方法[转]
          this.defSound();
          // }
          // self.video[this.index].muted = false;
          if (localStorage.getItem('platform') === 'ios' && localStorage.getItem('client') === 'APP') {
            if (self.forVideos) {
              if (self.videoPlayIcon) {
                self.exchangeBtnStatus(self.videoPlayIcon, false);
              }
              if (self.playBtn) {
                self.exchangeBtnStatus(self.playBtn, false);
              }
            }
          } else {
            if (document.getElementById('toggle-btn-fwvideo' + "-" + this.hivideoid)) {

              document.getElementById('toggle-btn-fwvideo' + "-" + this.hivideoid).style.display = 'none';
            }

            if (self.videoPlayIcon) {
              // ? h5修复微信浏览器按钮图标
              if (this.userAgent.match(/micromessenger/i) !== null) {
                if (!self.video[this.index].paused) {
                  self.exchangeBtnStatus(self.videoPlayIcon, false);
                }
              } else {
                self.exchangeBtnStatus(self.videoPlayIcon, false);

              }
            }
            if (self.playBtn) {
              self.exchangeBtnStatus(self.playBtn, false);
            }
          }

        } else {
          self.video[self.index].pause();
          console.log('暂停');
          if (document.getElementById('toggle-btn-fwvideo' + "-" + self.hivideoid)) {
            document.getElementById('toggle-btn-fwvideo' + "-" + self.hivideoid).style.display = 'block';
          }
          if (self.videoPlayIcon) {
            self.exchangeBtnStatus(self.videoPlayIcon, true);
          }
          if (self.playBtn) {
            self.exchangeBtnStatus(self.playBtn, true);
          }
        }
      });
    });

    return self;
  }
  bindAutoHideControlsEvent() {
    const self = this;

    const showOrHideControls = (isShow) => {
      isShow ? this.removeClass(self.videoBar, "none") : this.addClass(self.videoBar, "none");
    };

    const ticker = () => {
      // autoHide为true并且正在播放视频
      if (self.options.autoHide && !self.video[this.index].paused) {
        showOrHideControls(false);
      }
    };
    let timerId = setTimeout(ticker, 10000);

    ["mousemove"].forEach((type) => {
      self.videoParent.addEventListener(type, (event) => {
        if (timerId) {
          clearInterval(timerId);
        }
        showOrHideControls(true);
        timerId = setTimeout(ticker, 10000);
      });
    });
    return self;
  }
  bindMuteEvent() {
    const self = this;
    if (self.muteBtn) {
      self.muteBtn.addEventListener("click", () => {
        if (self.video[this.index].muted) {
          self.video[this.index].muted = false;
          self.volumebar.value = self.volume;

          self.exchangeBtnStatus(this.muteBtn, true);
        } else {
          self.video[this.index].muted = true;
          self.volumebar.value = 0;
          self.exchangeBtnStatus(this.muteBtn, false);
        }
      });
    }


    return self;
  }
  bindTimeChangeEvent() {
    const self = this;
    // 拖动时间进度
    if (self.seekbar) {
      self.seekbar.addEventListener("change", () => {
        // const time = parseFloat(self.video[this.index].duration * (this['value'] / 100)).toFixed(2);
        const currentValue = self.seekbar.value;
        // const timeStr = self.video[this.index].duration * (currentValue / 100) + '';
        // const testTime = parseFloat(timeStr).toFixed(2);
        self.video[this.index].currentTime = (self.video[this.index].duration * (currentValue / 100)).toFixed(2);
      });
    }

    // video事件更新
    if (self.video && self.video[this.index]) {
      self.video[this.index].addEventListener("timeupdate", () => {
        const val = (100 / self.video[this.index].duration) * self.video[this.index].currentTime;
        self.seekbar.value = val;
        // 更新当前时间
        self.curTimeSpan.innerText = this.getTimeBySecond(self.video[this.index].currentTime);
      });

      // 媒体数据加载完成
      if (!this.forVideos) {
        self.video[this.index].addEventListener("loadedmetadata", () => {
          self.totalTimeSpan.innerText = this.getTimeBySecond(self.video[this.index].duration);
          console.log('媒体数据加载完成~', this.index);

        });
      }

      self.video[this.index].addEventListener("ended", () => {
        if (this.forVideos) {
          self.video[this.index].play();

        } else {
          self.video[this.index].pause();
          if (document.getElementById('toggle-btn-fwvideo' + "-" + this.hivideoid)) {
            document.getElementById('toggle-btn-fwvideo' + "-" + this.hivideoid).style.display = 'block';
          }
          if (self.videoPlayIcon) {
            self.exchangeBtnStatus(self.videoPlayIcon, true);
          }
          self.video[this.index].currentTime = 0;
          self.exchangeBtnStatus(self.playBtn, true);

        }

      });

      self.volume = self.volumebar.value;
      self.video[this.index].volume = self.volumebar.value / 100;
      self.volumebar.addEventListener("change", () => {
        const currentVolumeValue = self.volumebar.value;
        self.video[this.index].volume = currentVolumeValue / 100;
        self.volume = currentVolumeValue;
        if (currentVolumeValue === 0) {
          self.video[this.index].muted = true;
          self.exchangeBtnStatus(self.muteBtn, false);
        } else {
          self.video[this.index].muted = false;
          self.exchangeBtnStatus(self.muteBtn, true);
        }
      });
    }
    return self;
  }
  config() {
    const self = this;
  }
  /**
   * querySelectorAll工厂，以备兼容性修改
   *  {NodeList}
   */
  querySelectorAll(selector) {
    return document.querySelectorAll(selector);
  }
  /**
   * querySelector工厂，以备兼容性修改
   *  selector
   *  parentEle
   *  {Element}
   */
  querySelector(selector, parentEle) {
    return parentEle ? parentEle.querySelector(selector) : document.querySelector(selector);
  }
  queryById(selector) {
    return document.getElementById(selector);
  }
  isFullScreen() {
    // tslint:disable-next-line:no-string-literal
    return window.document['fullscreenElement'] || document['webkitFullscreenElement'] || document['mozFullScreenElement']
      // tslint:disable-next-line:no-string-literal
      || document['msFullscreenElement'];
  }
  /**
   * 获取class
   */
  getClass(elem) {
    return elem.getAttribute && elem.getAttribute("class") || "";
  }
  /**
   * 添加class
   */
  addClass(ele, value) {
    if (value) {
      let curValue = this.getClass(ele);
      if (curValue.indexOf(value) === -1) {
        curValue = curValue + " " + value;
      }
      ele.setAttribute("class", curValue.trim());
    }
  }
  /**
   * 删除class
   */
  removeClass(ele, value) {
    if (value) {
      let curValue = this.getClass(ele);
      if (curValue.indexOf(value) > -1) {
        curValue = (" " + curValue + " ").replace(" " + value + " ", " ");
      }
      ele.setAttribute("class", curValue.trim());
    }
  }
  /**
   * 元素是否存在值为@{value}的class
   */
  hasClass(ele, value) {
    let has = false;
    if (value) {
      const curValue = this.getClass(ele);
      if (curValue.indexOf(value) > -1) {
        has = true;
      }
    }
    return has;
  }
  /**
   * 控制播放按钮 隐藏或者显示
   */
  exchangeBtnStatus(ele, isOn) {
    if (!ele) { return; }
    const onClass = "onBtn", offClass = "offBtn";
    if (isOn) {
      this.removeClass(ele, offClass);
      this.addClass(ele, onClass);
    } else {
      this.removeClass(ele, onClass);
      this.addClass(ele, offClass);
    }
  }
  /**
   * 获取time格式字符串
   */
  getTimeBySecond(second: any) {
    // tslint:disable-next-line:radix
    const hour = parseInt((second / (60 * 60)).toFixed(0));
    // tslint:disable-next-line:radix
    const minute = parseInt(((second / 60) % 60).toFixed(0));
    // tslint:disable-next-line:radix
    const subSecond = parseInt((second % 60).toFixed(0));
    // tslint:disable-next-line:max-line-length
    return (hour > 0 ? ((hour < 10 ? "0" + hour : hour) + ":") : "") + (minute < 10 ? "0" + minute : minute) + ":" + (subSecond < 10 ? "0" + subSecond : subSecond);
  }
  openPage(event, link) {
    this.video[this.index].pause();
    this.pageModalService.openPage(link);
    if (document.getElementById('toggle-btn-fwvideo' + "-" + this.hivideoid)) {
      document.getElementById('toggle-btn-fwvideo' + "-" + this.hivideoid).style.display = 'block';
    }
    if (this.videoPlayIcon) {
      this.exchangeBtnStatus(this.videoPlayIcon, true);
    }
    if (this.playBtn) {
      this.exchangeBtnStatus(this.playBtn, true);
    }
    event.stopPropagation();
  }
  soundOnOff(videoData) {
    if (videoData.sound === 'on') {
      videoData.sound = 'off';
      this.video[this.index].muted = true;

    } else {
      videoData.sound = 'on';
      this.video[this.index].muted = false;
    }
  }
  defSound() {
    if (this.videoData) {
      if (this.videoData.sound === 'on') {
        this.video[this.index].muted = false;
      } else {
        this.video[this.index].muted = true;
      }
    }
  }

  ngOnDestroy(): void {
  }

}
